package org.jdcenter.server;

import java.net.URL;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdcenter.Constants;
import org.jdcenter.server.deployment.DelegateDeployer;
import org.jdcenter.server.xb.ParserFactory;
import org.jdcenter.server.xb.metadata.BootstrapMateData;
import org.jdcenter.server.xb.metadata.PluginsMateData;
import org.jdcenter.server.xb.parser.AbstractParser;
import org.jdcenter.server.xb.visitors.PluginsVisitor;

/**
 * @author miao
 * @since 2008-11-18
 *
 */
public class ServerImpl extends AbstractServer{
	
	public static Log log = LogFactory.getLog(ServerImpl.class);
	
	private final static String bootstrap = "bootstrap.xml";
	
	protected void doStart() throws Exception{
		ParserFactory parserFactory = ParserFactory.getInstance();
		PluginsURLClassLoader pluginsLoader = PluginsURLClassLoader.createClassLoader(getClass().getClassLoader());
		AbstractParser<BootstrapMateData> bootParser = parserFactory.createParser(Constants.bootstrapParser,getClass().getClassLoader());
		AbstractParser<PluginsMateData> pluginsParser = parserFactory.createParser(Constants.pluginsParser,getClass().getClassLoader());
		ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
		try{		
			Thread.currentThread().setContextClassLoader(pluginsLoader);
			URL bootstrapUrl = new URL(getConfUrl(),bootstrap);
			BootstrapMateData mateData = bootParser.parse(bootstrapUrl);
			List<String> urls = mateData.getUrls();
			for(String url:urls){
				//log.debug(getPluginsUrl(url));
				PluginsMateData pMateData = pluginsParser.parse(getPluginsUrl(url));
				pMateData.accept(new PluginsVisitor());
			}
			DelegateDeployer.getInstance().deploy();
		}finally{
			Thread.currentThread().setContextClassLoader(oldLoader);
		}		
	} 

}
